<?php

namespace july\julyadmin\builder\table;

use july\julyadmin\builder\traits\actions\HasBase;

/**
 * 左边树形列表
 * @author July
 */
class JsTree
{
    use HasBase;
    //左边树形列表
    public $tree;
    //左边属性列表字段名称
    protected $field = '';
    //表格类型
    protected $tableType = 'table';

    /**
     * 设置表格类型
     * @param string $type 表格类型table,treeTable
     * @return  this
     */
    public function tableType($type = 'table')
    {
        $this->tableType = $type;
        return $this;
    }

    /**
     * 添加组件
     * @param  string $field          字段
     * @param  string $title          名称
     * @return this
     */
    public function __construct($field = '', $title = '')
    {
        $tree           = new \stdClass();
        $tree->field    = $field;
        $tree->title    = $title;
        $tree->open     = 'true';
        $tree->options  = [];
        $tree->dataUrl  = '';
        $tree->tableId = '';
        //内容
        $tree->value = '';
        $this->tree  = $tree;
        return $this;
    }

    /**
     * 绑定表格id
     * @param $tableId  表格id，自己定义\
     */
    public function bindTableId($tableId = '')
    {
        $this->tree->tableId = $tableId;
        return $this;
    }

    /**
     * 设置是否展开
     * @param boolean $is_open 是否展开
     */
    public function setOpen($is_open = true)
    {
        $this->tree->open = $is_open ? 'true' : 'false';
        return $this;
    }

    /**
     * 设置select请求地址
     * @param  string $url 请求地址
     * @return this
     */
    public function dataUrl($url = "")
    {
        $this->tree->dataUrl = is_string($url) ? $url : (string) $url;
        return $this;
    }

    /**
     * 设置select 数据
     * @param  array $options 下拉数据，键值对数组
     * @return this
     */
    public function options($options = [])
    {
        $this->tree->options = $options;
        return $this;
    }

    /**
     * 设置搜索表单默认值
     * @param  string $value 默认值
     * @return this
     */
    function default($value = '') {
        $this->tree->value = $value;
        return $this;
    }
    /**
     * 渲染搜索表單
     */
    public function render()
    {

        $html         = '';
        $script       = '';
        $html .= <<<EOT
                <link rel="stylesheet" type="text/css" href="/static/assets/admin/js/jstree/style.min.css" rel="stylesheet">
                <link rel="stylesheet" type="text/css" href="/static/assets/admin/js/jstree/mystyle.css" rel="stylesheet">
                <script type="text/javascript" src="/static/assets/admin/js/jstree/jstree.min.js"></script>

                <div id="page-left-tree"></div>

EOT;
        
        $script.=<<<EOT
        <script>
            //递归展开关闭
            function leftTreeExpandAllNodes(array,open) {
                //递归展开关闭
                array.forEach((item,index) => {
                    item.checked = false;
                    if(item.hasOwnProperty('state')){
                        array[index].state.opened = open;
                    }else{
                        array[index].state = {opened:open};
                    }
                    if(item.hasOwnProperty('children') && item.children){
                        leftTreeExpandAllNodes(item.children,open);
                    }
                });
                return array;
            }
        </script>
EOT;
        if ($this->tree->options && !$this->tree->dataUrl) {
            $options = json_encode($this->tree->options);
            $script .= <<<EOT

                    <script>
                        
                        var options = {$options};
                        options = leftTreeExpandAllNodes(options,{$this->tree->open});
                        options.unshift({
                            id:"all",
                            text:"全部"
                        })

                        $('#page-left-tree').jstree({
                            'core' : {
                                'animation' : 0,
                                'check_callback' : true,
                                'force_text' : true,
                                'themes' : {
                                    'responsive': false
                                },
                                'data' : options
                            },
                            "types" : {
                                'default' : {
                                    'icon' : 'mdi mdi-folder-outline'
                                },
                                'file' : {
                                    'icon' : 'mdi mdi-file-outline'
                                }
                            },
                            "plugins" : ["dnd", "search", "types", "wholerow"]
                        });
                        $('#page-left-tree').on("activate_node.jstree", function (obj, e) {
                            var where = layui.{$this->tableType}.getOptions('{$this->tree->tableId}').where;
                            if(e.node.id!='all'){
                                where['search[{$this->tree->field}]'] = e.node.id;
                            }else{
                                if(where.hasOwnProperty('search[{$this->tree->field}]')){
                                    delete where['search[{$this->tree->field}]'];
                                }
                            }

                            layui.{$this->tableType}.reload('{$this->tree->tableId}',{
                                where:where,
                                page: {
                                    curr: 1
                                }
                            });

                        });
                        setTimeout(function(){
                            $('#page-left-tree').jstree('select_node', 0);
                            var rootNode = $('#page-left-tree').jstree(true).get_node('#');
                        },10);
                    </script>
EOT;
        } else if (!$this->tree->options && $this->tree->dataUrl) {

            $script .= <<<EOT
                    <script>
                        $.ajax({
                            type:'GET',
                            url:'{$this->tree->dataUrl}',
                            data:{},
                            dataType:'json',
                            success:function(res) {
                                if(res.hasOwnProperty("code") && res.code==1){
                                    var options = res.data;
                                    options.map((item,index)=>{
                                        if(!item.hasOwnProperty("state") || !item.state.hasOwnProperty("opened")){
                                            options[index].state = {
                                                "opened":{$this->tree->open}
                                            }
                                        }
                                    });
                                    options = leftTreeExpandAllNodes(options,{$this->tree->open});
                                    options.unshift({
                                        id:"all",
                                        text:"全部"
                                    })

                                    $('#page-left-tree').jstree({
                                        'core' : {
                                            'animation' : 0,
                                            'check_callback' : true,
                                            'force_text' : true,
                                            'themes' : {
                                                'responsive': false
                                            },
                                            'data' : options
                                        },
                                        "types" : {
                                            'default' : {
                                                'icon' : 'mdi mdi-folder-outline'
                                            },
                                            'file' : {
                                                'icon' : 'mdi mdi-file-outline'
                                            }
                                        },
                                        "plugins" : ["dnd", "search", "types", "wholerow"]
                                    });
                                    $('#page-left-tree').on("activate_node.jstree", function (obj, e) {
                                        var where = layui.{$this->tableType}.getOptions('{$this->tree->tableId}').where;
                                        if(e.node.id!='all'){
                                            where['search[{$this->tree->field}]'] = e.node.id;
                                        }else{
                                            if(where.hasOwnProperty('search[{$this->tree->field}]')){
                                                delete where['search[{$this->tree->field}]'];
                                            }
                                        }
                                        layui.{$this->tableType}.reloadData('{$this->tree->tableId}',{
                                            where:where,
                                            page: {
                                                curr: 1
                                            }
                                        });
                                    });
                                    setTimeout(function(){
                                        $('#page-left-tree').jstree('select_node', 0);
                                        var rootNode = $('#page-left-tree').jstree(true).get_node('#');
                                    },10);
                                }else{
                                    layer.msg(('{$this->tree->title}'?'{$this->tree->title}':'左边树形列表')+'加载失败！',{
                                        icon:5,
                                        time:2000,
                                        shade:[0.6,'#000',false]
                                    });
                                }
                            },
                            error:function(res){
                                layer.msg(JSON.stringify(res),{
                                    icon:5,
                                    time:2000,
                                    shade:[0.6,'#000',false]
                                });
                            }
                        });
                        
                        $('.chevron-toggle').click(function(e){
                            if($('.main-layout-left').css('left')=='0px'){
                                $('.main-layout-left').animate({left:-225});
                                $('.main-layout-right').animate({marginLeft:'0px'});
                            }else{
                                $('.main-layout-left').animate({left:0});
                                $('.main-layout-right').animate({marginLeft:'225px'});
                            }
                            setTimeout(function(){
                                $(window).resize();
                            },300);
                        });         
                    </script>
EOT;
        }

        return ['html' => $html, 'script' => $script];
    }
}
